package epam.concurrency.lab2.task4;

import java.math.BigInteger;
import java.util.concurrent.atomic.AtomicReference;

/**
 * Thread-safe constructor of geometric progression
 * Construct the next number in sequence [1,2,4,8,16...]
 * @author Iurii Miedviediev
 * @version 1.0 Build 17.08.2014
 */
public class LockFreeSequence {

    private static final AtomicReference<BigInteger> NUMBER = new AtomicReference<>(BigInteger.ONE);

    public BigInteger next() {
        BigInteger old = NUMBER.get();
        while (!NUMBER.compareAndSet(old, old.add(old))) {
            old = NUMBER.get();
        }
        return old;
    }
}
